package com.bolingcavalry.crm.utils;

import com.base.RoleEnum;

import java.util.List;

public class RolePermissionUtils {

    /**
     * 判断当前登录人是否有权限查看某个服务单（根据接收人角色）
     *
     * @param receiverRoles 接收人角色列表
     * @param loginUserRoles 登录人角色列表
     * @return 是否有权限
     */
    public static boolean hasAccess(List<String> receiverRoles, List<String> loginUserRoles) {
        if (receiverRoles == null || loginUserRoles == null) return false;

        for (String receiverRoleCode : receiverRoles) {
            RoleEnum receiverRole = RoleEnum.fromCode(receiverRoleCode);

            for (String loginRoleCode : loginUserRoles) {
                RoleEnum loginRole = RoleEnum.fromCode(loginRoleCode);

                // 如果 loginRole 是 receiverRole 的上级领导 → 放行
                if (isLeaderOf(loginRole, receiverRole)) {
                    return true;
                }
            }
        }

        return false;
    }

    /**
     * 判断一个角色是否是另一个角色的上级领导
     */
    private static boolean isLeaderOf(RoleEnum leader, RoleEnum subordinate) {
        // 如果没有归属部门，不考虑上下级关系
        if (subordinate.getDepartment() == null) {
            return false;
        }

        // 判断 leader 是否是该部门的领导，并且确实拥有领导权限
        return leader.isLeader()
                && leader.getDepartment() != null
                && leader.getDepartment().equals(subordinate.getDepartment());
    }
}